package com.javalsj.common.web.autoconfigure;

import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import feign.Request;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Retryer;

/**
 * @description FeignClient配置，解决传递请求头的问题
 * @author WANGJIHONG
 * @date 2019年6月3日 下午12:01:46
 * @Copyright 版权所有 (c) www.javalsj.com
 * @memo 无备注说明
 */
@Configuration
public class CommonWebFeignAutoConfiguration {

	private Logger logger = LoggerFactory.getLogger(CommonWebFeignAutoConfiguration.class);

	@Bean
	public Retryer feignRetryer() {
        return Retryer.NEVER_RETRY;
    }
	
	@Bean
	public RequestInterceptor requestInterceptor() {
		return new RequestInterceptor() {
			@Override
			public void apply(RequestTemplate template) {
				ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
						.getRequestAttributes();
				HttpServletRequest request = attributes.getRequest();
				Enumeration<String> headerNames = request.getHeaderNames();
				if (headerNames != null) {
					while (headerNames.hasMoreElements()) {
						String name = headerNames.nextElement();
						if (name.equalsIgnoreCase(HttpHeaders.ACCEPT_ENCODING)) {
							template.header(name, "deflate");
							continue;
						}
						boolean isExist = false;
						Map<String, Collection<String>> headers = template.headers();
						for (String templateHeaderName : headers.keySet()) {
							if (name.equalsIgnoreCase(templateHeaderName)) {
								isExist = true;
							}
						}
						if (!isExist) {
							String values = request.getHeader(name);
							template.header(name, values);
						}
					}
				}
				Enumeration<String> bodyNames = request.getParameterNames();
				StringBuffer body = new StringBuffer();
				if (bodyNames != null) {
					while (bodyNames.hasMoreElements()) {
						String name = bodyNames.nextElement();
						String values = request.getParameter(name);
						body.append(name).append("=").append(values).append("&");
					}
				}
				if (body.length() != 0) {
					body.deleteCharAt(body.length() - 1);
					template.body(Request.Body.bodyTemplate(body.toString(), Charset.defaultCharset()));
					logger.info("feign interceptor body:{}", body.toString());
				}
			}
		};
	}
}
